﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a role.
    /// </summary>
    public class CreateRole : CreateAuditable<RoleEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("ACL");
            }
        }

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public RoleFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            if(String.IsNullOrWhiteSpace(Code))
                return Err.Of<RoleEntity>().NotValid("Code");
            return base.Validate(uow);
        }

        protected override void Construct(IUnitOfWork uow, RoleEntity entity)
        {
            base.Construct(uow, entity);

            entity.Code = Code.TrimToLen(10);
            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the role.
    /// </summary>
    public class UpdateRole : UpdateAuditable<RoleEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("ACL");
            }
        }

        /// <summary>
        /// Gets or sets the code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public RoleFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            if(String.IsNullOrWhiteSpace(Code))
                return Err.Of<RoleEntity>().NotValid("Code");
            return base.Validate(uow);
        }

        protected override void Revise(IUnitOfWork uow, RoleEntity entity)
        {
            base.Revise(uow, entity);

            entity.Code = Code.TrimToLen(10);
            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the role.
    /// </summary>
    public class DeleteRole : DeleteEntity<RoleEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("ACL");
            }
        }

        #endregion

        #region Utilities

        protected override void Destruct(IUnitOfWork uow, RoleEntity entity)
        {
            foreach(var i in entity.Permissions.ToList())
            {
                uow.Execute(new UnmapPermissionFromRole
                {
                    ChildID = i.EntityID,
                    EntityID = entity.EntityID
                });
            }
            foreach(var i in entity.Accounts)
            {
                uow.Execute(new UnmapAccountFromRole
                {
                    EntityID = i.EntityID,
                    ChildID = entity.EntityID
                });
            }
            base.Destruct(uow, entity);
        }

        #endregion
    }

    /// <summary>
    /// Gets the role by identifier.
    /// </summary>
    public class GetRole : GetEntity<RoleEntity>,
        IApiOperation
    {
    }

    /// <summary>
    /// Gets the role by code.
    /// </summary>
    public class GetRoleByCode : QueryEntity<RoleEntity>,
        IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets or sets the role code.
        /// </summary>
        public string Code
        {
            get;
            set;
        }

        #endregion

        #region Options

        protected override bool Cacheable
        {
            get
            {
                return true;
            }
        }

        #endregion

        #region Utilities

        protected override IQueryable<RoleEntity> Build(IUnitOfWork uow, IQueryable<RoleEntity> query)
        {
            string code = StringHelper.EnsureNotNull(Code).TrimToLen(10);
            return base.Build(uow, query).Where(x => x.Code.Equals(code));
        }

        #endregion
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over role collection.
    /// </summary>
    public class SearchRoles : SearchOperation<RoleEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchRoles()
        {
            SortDir = SortDirection.Ascending;
            SortBy = new []
            {
                RoleSortBy.ID
            };
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the account identifier.
        /// </summary>
        public int? AccountID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the permission identifier.
        /// </summary>
        public int? PermissionID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public RoleFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort by.
        /// </summary>
        public RoleSortBy[] SortBy
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<RoleEntity> Build(IUnitOfWork uow, IQueryable<RoleEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            if(AccountID.HasValue)
                query = query.Where(x => x.Accounts.Any(i => i.EntityID == AccountID.Value));
            if(PermissionID.HasValue)
                query = query.Where(x => x.Permissions.Any(i => i.EntityID == PermissionID.Value));
            if(SortBy != null)
            {
                for(int i = 0; i < SortBy.Length; i++)
                {
                    switch(SortBy[i])
                    {
                        case RoleSortBy.Name:
                            query = query.OrderBy(x => x.Name, SortDir, i != 0);
                            break;
                        case RoleSortBy.CreatedOn:
                            query = query.OrderBy(x => x.CreatedOn, SortDir, i != 0);
                            break;
                        default:
                            query = query.OrderBy(x => x.EntityID, SortDir, i != 0);
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
    }

    #endregion

    #region __Map__

    /// <summary>
    /// Maps the permission to role.
    /// </summary>
    public class MapPermissionToRole : MapOperation<RoleEntity, PermissionEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("ACL");
            }
        }

        #endregion
    }

    /// <summary>
    /// Unmaps the permission from role.
    /// </summary>
    public class UnmapPermissionFromRole : UnmapOperation<RoleEntity, PermissionEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("ACL");
            }
        }

        #endregion
    }

    #endregion
}
